package com.changgou.oauth.controller;

import com.changgou.oauth.service.LoginService;
import com.changgou.oauth.util.CookieUtil;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 描述
 *
 * @author ljh
 * @version 1.0
 * @package com.changgou.oauth.controller *
 * @Date 2019-12-4
 * @since 1.0
 */
@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private LoginService loginService;

    private static final String grant_type="password";
    private static final String clientId="changgou";
    private static final String clientSecret="changgou";


    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    //Cookie生命周期
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    /**
     * 要登录  用户在页面输入用户名和密码 由该controller的方法来接收 (模拟刚才的POSTman发送请求申请令牌 返回给用户)
     */
    @RequestMapping("/login")
    public Result<Map> login(String username, String password) {
        //1.获取用户名和密码
        //2.设置clientid 和client secret
        //3.设置授权模式 grant_type 为密码模式(写死)
        //4.使用resttemplate来模拟(POSTman)发送请求 申请令牌信息
        //5.返回
        Map result= loginService.login(username,password,grant_type,clientId,clientSecret);
        saveCookie(result.get("access_token").toString());

        return new Result<Map>(true, StatusCode.OK,"登录成功",result);
    }

    private void saveCookie(String token){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response,cookieDomain,"/","Authorization",token,cookieMaxAge,false);
    }

}
